package com.test.xshang.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @BelongsProject: simpleframework
 * @BelongsPackage: com.Xshang.reflect
 * @Author: xshang
 * @CreateTime: 2023-06-23  20:32
 * @Description: 通过反射获取成员变量 并赋值
 * @Version: 1.0
 */
public class FieldCollector {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取class对象
        Class<?> clazz = Class.forName("com.test.xshang.reflect.ReflectTarget");

        // 获取所有字段
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        Field nameField = clazz.getField("name");
        ReflectTarget reflectTarget = (ReflectTarget) clazz.getConstructor().newInstance();
        nameField.set(reflectTarget,"反射一号");
        System.out.println(reflectTarget.name);

    }

}
